package com.seveneight.baijiesteward.ui.main.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.seveneight.baijiesteward.R;
import com.seveneight.baijiesteward.base.BaseActivity;
import com.seveneight.baijiesteward.bean.AnyBean;
import com.seveneight.baijiesteward.bean.CardBean;
import com.seveneight.baijiesteward.bean.CreditBean;
import com.seveneight.baijiesteward.http.AppConfig;
import com.seveneight.baijiesteward.http.HttpConfig;
import com.seveneight.baijiesteward.http.MyCallBack;
import com.seveneight.baijiesteward.ui.user.activity.CreditCardListActivity;
import com.seveneight.baijiesteward.ui.user.activity.ManagerCardActivity;
import com.seveneight.baijiesteward.ui.user.model.BankAddRepayModel;
import com.seveneight.baijiesteward.utils.DateUtil;
import com.seveneight.baijiesteward.utils.GlideLoader;
import com.seveneight.baijiesteward.utils.MD5Parse;
import com.seveneight.baijiesteward.utils.StringUtils;
import com.seveneight.baijiesteward.utils.ToastUtil;
import com.seveneight.baijiesteward.views.cover.PasswordInputView;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 预约还款
 */
public class BankPaymentReservationActivity extends BaseActivity implements View.OnClickListener{
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.account_money)
    TextView account_money;
    @BindView(R.id.iv_creditlogo)
    ImageView iv_creditlogo;
    @BindView(R.id.tv_creditbank)
    TextView tv_creditbank;
    @BindView(R.id.tv_creditNo)
    TextView tv_creditNo;
    @BindView(R.id.iv_debitlogo)
    ImageView iv_debitlogo;
    @BindView(R.id.tv_debitbank)
    TextView tv_debitbank;
    @BindView(R.id.tv_debitNo)
    TextView tv_debitNo;
    @BindView(R.id.payment_date)
    TextView payment_date;
    @BindView(R.id.et_input)
    TextView et_input;
    @BindView(R.id.user_rate)
    TextView user_rate;
    @BindView(R.id.user_brokerage)
    TextView user_brokerage;
    PasswordInputView password;
    private CreditBean creditBean;
    private CreditBean cardBean;
//    private CardBean cardBean;
    Long time=null;
    BankAddRepayModel api=new BankAddRepayModel();
    private PopupWindow mPoupWindow = null;
    DecimalFormat df=new DecimalFormat("######0.00");

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_bank_payment_reservation);
    }

    @Override
    protected void initView() {
        tv_title.setText("预约还款");

    }

    @Override
    protected void initData() {
        user_brokerage.setText(userBean.getBrokerage()+"元");
        user_rate.setText(userBean.getRate());

    }

    @Override
    protected void setListener() {
        et_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!StringUtils.isEmpty(et_input.getText().toString())){
                    Double money=Double.parseDouble(et_input.getText().toString());
                    if (money>0){
                        account_money.setText(df.format((money-money*Double.parseDouble(userBean.getRate())-Double.parseDouble(userBean.getBrokerage()))));
                    }else {
                        account_money.setText("0");
                    }
                }else {
                    account_money.setText("0");
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            switch(requestCode){
                case 0:
                    creditBean = (CreditBean) data.getSerializableExtra("bean");
                    initCreditCrd();
                    break;
                case 1:
                    cardBean = (CreditBean) data.getSerializableExtra("bean");
                    initDebitCard();
                    break;
            }
        }
    }
    private void initDebitCard() {
        GlideLoader.displayImg(this, HttpConfig.SOURCE_URL + cardBean.getIcoUrl(), iv_debitlogo);
        tv_debitbank.setText(cardBean.getBankName());
        tv_debitNo.setText("尾号" + cardBean.getCreditCardNo().substring(cardBean.getCreditCardNo().length() - 4) + " 信用卡");
    }
    private void initCreditCrd() {
        GlideLoader.displayImg(this, HttpConfig.SOURCE_URL + creditBean.getIcoUrl(), iv_creditlogo);
        tv_creditbank.setText(creditBean.getBankName());
        tv_creditNo.setText("尾号" + creditBean.getCreditCardNo().substring(creditBean.getCreditCardNo().length() - 4) + " 信用卡");
    }
    public void selectDate(){
        DatePickDialog dialog = new DatePickDialog(this);
        //设置上下年分限制
        dialog.setYearLimt(0);
        //设置标题
        dialog.setTitle("选择时间");
        //设置类型
        dialog.setType(DateType.TYPE_ALL);
        //设置消息体的显示格式，日期格式
        dialog.setMessageFormat("yyyy-MM-dd");
        //设置选择回调
        dialog.setOnChangeLisener(null);
        //设置点击确定按钮回调
        dialog.setOnSureLisener(new OnSureLisener() {
            @Override
            public void onSure(Date date) {
                time=date.getTime();
                payment_date.setText(DateUtil.dateFormatMonthDay(date.getTime()));
            }
        });
        dialog.show();
    }

    @OnClick({R.id.iv_back,R.id.layout_gocredit,R.id.layout_godebit,R.id.select_time,R.id.tv_next})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.layout_gocredit:
                Intent i = new Intent(this, CreditCardListActivity.class);
                startActivityForResult(i, 0);
                break;
            case R.id.layout_godebit:
                Bundle bundle = new Bundle();
//                bundle.putInt("type", 2);
//                Intent intent = new Intent(this, ManagerCardActivity.class);
//                intent.putExtras(bundle);
//                startActivityForResult(intent, 1);
                Intent intent = new Intent(this, CreditCardListActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.select_time:
                selectDate();
                break;
            case R.id.tv_next:
                if (StringUtils.isEmpty(et_input.getText().toString())){
                    ToastUtil.show(this,"请输入扣除金额");
                    return;
                }
                if (creditBean ==null){
                    ToastUtil.show(this,"请选择扣款卡");
                    return;
                }
                if (cardBean ==null){
                    ToastUtil.show(this,"请选择还款卡");
                    return;
                }
                if (time==null){
                    ToastUtil.show(this,"请还款日期结算卡");
                    return;
                }
                remoreData();

                break;
        }
    }

    private View mPoupView = null;
    protected LayoutInflater mInflater;
    /**
     * 底部PopupWindow
     */
    public void showBottomPopupWindow(View secroll_view) {
        if (mPoupView == null) {
            mInflater = LayoutInflater.from(this);
            mPoupView = mInflater.inflate(R.layout.window_input_password_layout, null);
            bindPopMenuEvent(mPoupView);
        }
        mPoupWindow = new PopupWindow(mPoupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//            mPoupWindow.setAnimationStyle(R.style.PopupAnimation);
        mPoupWindow.setTouchable(true);
        mPoupWindow.setFocusable(true);
        mPoupWindow.setOutsideTouchable(true);
        mPoupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        mPoupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
        ColorDrawable dw = new ColorDrawable(00000000);
        mPoupWindow.setBackgroundDrawable(dw);
        mPoupWindow.showAtLocation(secroll_view, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.7f);
    }
    public void bindPopMenuEvent(View view){
        password=view.findViewById(R.id.password);
        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (password.getText().length()==6){
                    mPoupWindow.dismiss();
                    psw=password.getText().toString();
                    password.setText("");
                    hintKbTwo();
                    requstData();
                }
            }
        });
    }
    private void hintKbTwo() {
        @SuppressLint("WrongConstant") InputMethodManager localInputMethodManager = (InputMethodManager)getSystemService("input_method");
        if ((localInputMethodManager.isActive()) && (getCurrentFocus() != null) && (getCurrentFocus().getWindowToken() != null)) {
            localInputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 2);
        }
    }
    String psw;
    public void remoreData(){
        new MaterialDialog.Builder(activity)
                .title("请再次确认")
                .titleColorRes(R.color.colorAccent)
                .content("扣除金额:"+Double.parseDouble(et_input.getText().toString())+"\n到账金额:"+df.format((Double.parseDouble(et_input.getText().toString())-Double.parseDouble(et_input.getText().toString())*Double.parseDouble(userBean.getRate()))-Double.parseDouble(userBean.getBrokerage())))
                .contentColorRes(R.color.graytext)
                .backgroundColorRes(R.color.white)
                .negativeColorRes(R.color.mainblue)
                .negativeText(R.string.negative)
                .positiveColorRes(R.color.mainblue)
                .positiveText(R.string.positive)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();

                        showBottomPopupWindow(findViewById(R.id.reservation_layout));
                    }
                })
                .build().show();
    }
    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        this.getWindow().setAttributes(lp);
    }


    //    window_input_password_layout
    public void requstData(){
        Map<String,Object> params=new HashMap<>();
        params.put("OutCardId",creditBean.getCreditCardID());
        params.put("OutCardNo",creditBean.getCreditCardNo());
        params.put("InCardId",cardBean.getCreditCardID());
        params.put("InCardNo",cardBean.getCreditCardNo());
        params.put("Amount",et_input.getText().toString());
        params.put("ExecuteTime",DateUtil.dateLong(time));//执行时间Date
        params.put("TradePassword", MD5Parse.parseStr(psw));//交易密码
        api.getBankList(this, jsonFormat.AddObject(params), new MyCallBack<AnyBean>() {
            @Override
            public void onSuccess(AnyBean anyBean) {
                setResult(RESULT_OK);
                Toast.makeText(getContext(),"预约成功",Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onFailed() {
                password.setText("");
            }
        });
    }
}
